package com.xing.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.xing.Utils.Result;
import com.xing.config.JSONUtils;
import com.xing.entity.MessageEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2024/1/12 17:08
 */
@Slf4j
@ServerEndpoint(value = "/web/websocket")
@Component
public class WebsocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebsocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //用户ID
    private String userId;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在线数加1
        addOnlineCount();
        log.info("有新连接加入={}！当前连接数为{}",getUserId(),getOnlineCount());
        sendAll(getUserId()+"上线了");
        //获取用户ID
        getUserId();

        //发送“未读消息”
        sendMessage(getUnreadCountMsg());
    }

    private String getUnreadCountMsg() {
        return userId+"链接成功";
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        log.info("有一连接关闭={}！当前连接数为{}",getUserId(),getOnlineCount());
        sendAll(getUserId()+"下线了");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        MessageEntity messageEntity = JSONUtils.jsonToObj(message, MessageEntity.class);
        log.info("来自客户端的消息:{}",messageEntity);
        assert messageEntity != null;
        boolean user = User(messageEntity.getTo());
        if (!user){
            log.info("用户{}不在线",messageEntity.getTo());
        }else {
            for (WebsocketServer websocketServer : webSocketSet) {
                if (websocketServer.userId.equals(messageEntity.getTo())){
                    messageEntity.setServer("client");
//                    messageEntity.setTime(new Date().toString());
                    websocketServer.sendMessage(JSONUtils.objToJson(new Result().ok(messageEntity)));
                }
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
            log.info("websocket发送消息成功：{}", message);
        } catch (IOException e) {
            log.error("websocket服务端发送消息异常");
            e.printStackTrace();
        }
    }

    /**
     * 自定义方法
     */
    @Async
    public void sendUnreadCountMsgByUserId(String userId) {
        log.info("------------自定义方法------------,userId:{}", userId);
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        for (WebsocketServer item : webSocketSet) {
            if (userId.equals(item.userId)) {
                item.sendMessage("自定义方法");
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebsocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebsocketServer.onlineCount--;
    }

    /**
     * 从url获取入参“userId”
     *
     * @return
     */
    private String getUserId() {
        String userId = getParameterMap().get("userId");

        //如没有传递userId，则关闭连接
        if (StringUtils.isEmpty(userId)) {
            sendMessage("userId不能为空");
            log.error("userId不能为空");
            throw new RuntimeException("userId不能为空");
        }
        this.userId = userId;
        return userId;
    }

    /**
     * 获取会议id
     * @return
     */
    private String getRoomId() {
        String roomId = getParameterMap().get("roomId");

        //如没有传递userId，则关闭连接
        if (StringUtils.isEmpty(roomId)) {
            sendMessage("roomId不能为空");
            log.error("roomId不能为空");
            throw new RuntimeException("roomId不能为空");
        }
        this.userId = userId;
        return userId;
    }


    private HashMap<String, String> getParameterMap(){
        HashMap<String, String> map = new HashMap<>();

        String queryString = session.getQueryString();
        if(StringUtils.isEmpty(queryString) ){
            return map;
        }

        String[] split = queryString.split("&");
        for (String s : split) {
            if (s.contains("=")) {
                String[] strings = s.split("=");
                map.put(strings[0], strings[1]);
            }
        }
        return map;
    }

    public boolean User(String userId){
        for (WebsocketServer server : webSocketSet) {
            System.out.println(server.userId);
            if (server.userId.equals(userId)){
                return true;
            }
        }
        return false;
    }

    /**
     * 广播消息
     */
    public void sendAll(String message){
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setInfo(message);
        for (WebsocketServer server : webSocketSet) {
            server.sendMessage(JSONUtils.objToJson(new Result().ok(messageEntity)));
        }
    }
}
